package com.study.daily.algozuo.y2021.m10.day1020;

/**
 * BSAware
 *
 * @author Tom on 2021/10/20
 */
public class Code04_BSAware {
    public static void main(String[] args) {
        int[] arr = new int[]{7,3, 4, 5, 7, 9, 8, 12, 16, 21, 18, 18};
        System.out.println(minValue(arr));
    }

    public static int minValue(int[] arr) {
        if (arr == null || arr.length == 0) {
            return -1; // no exist
        }
        if (arr.length == 1 || arr[0] < arr[1]) {
            return 0;
        }
        if (arr[arr.length - 1] < arr[arr.length - 2]) {
            return arr.length - 1;
        }
        int left = 1;
        int right = arr.length - 2;
        int mid = 0;
        while (left < right) {
            mid = (left + right) / 2;
            if (arr[mid] > arr[mid - 1]) {
                right = mid - 1;
            } else if (arr[mid] > arr[mid + 1]) {
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return left;
    }

}
